﻿using Canon;
using EDSDKLib;
using Kaliko.ImageLibrary;
using Kaliko.ImageLibrary.Filters;
using DevTeam;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Aker;
using System.Drawing.Drawing2D;
using Extensions;
using Aker.DevTeam;
using System.Data;

namespace Aker
{
    public partial class CanonTaker : XPopupForm
    {
        public CanonTaker()
        {
            InitializeComponent();
        }

        #region Barcode
        //public delegate void BarcodeReadHandler(int Barcode);
        //public event BarcodeReadHandler BarcodeRead;
        //public void FireBarcodeRead(int Barcode)
        //{
        //    if (BarcodeRead != null)
        //        BarcodeRead(Barcode);
        //}
        //void portBarcodeScanner_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        //{
        //    string data = portBarcodeScanner.ReadExisting();

        //    if (data.EndsWith("\r\n"))
        //    {
        //        data = data.Replace("\r\n", "");

        //        //son hane parity ve tip alanları atılınca geri kalan çıplak barkod
        //        int barcode = int.Parse(data.Substring(0, data.Length - 1));

        //        FireBarcodeRead(barcode);
        //    }
        //}

        //private void InitBarcode()
        //{
        //    portBarcodeScanner = new System.IO.Ports.SerialPort(Properties.Settings.Default.BarcodeComPort);
        //    portBarcodeScanner.BaudRate = 57600;
        //    portBarcodeScanner.DataBits = 8;
        //    portBarcodeScanner.Parity = System.IO.Ports.Parity.Mark;
        //    portBarcodeScanner.StopBits = System.IO.Ports.StopBits.One;
        //    portBarcodeScanner.DtrEnable = true;
        //    portBarcodeScanner.Open();
        //    portBarcodeScanner.DataReceived += portBarcodeScanner_DataReceived;
        //    BarcodeRead += MainForm_BarcodeRead;
        //}

        //void MainForm_BarcodeRead(int Barcode)
        //{
        //    if (wait && Barcode > 0)
        //        Kaydet(fl);
        //    else
        //    {
        //        Code = Barcode;
        //        pictureBox1.Image = null;
        //        CameraHandler.TakePhoto();
        //    }

        //    wait = Barcode == 0;

        //}

        #endregion

        string latestFile;
        string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Photos";

        SDKHandler CameraHandler;

        private void CanonTaker_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (Environment.MachineName != "KGULCAN")
            {
                CloseSession();
                CameraHandler.Dispose();
            }
        }

        void CameraHandler_CameraHasShutdown(object sender, EventArgs e)
        {
            CloseSession();
        }

        private void CloseSession()
        {
            if (Environment.MachineName != "KGULCAN")
                CameraHandler.CloseSession();
        }

        private void CanonTaker_Load(object sender, EventArgs e)
        {
            this.FormClosing += CanonTaker_FormClosing;
            lblError.Text = "";
            if (Environment.MachineName != "KGULCAN")
                InitCamera();

            pen.DashStyle = DashStyle.Dash;

            if (Environment.MachineName != "KGULCAN")                
                Crop();            

            if (Environment.MachineName == "KGULCAN")
            {
                TakeGo.Visible = true;
                Crop();
            }

            btnOk.Text = Language.CameraViewer.UseThisImage;
            btnTake.Text = Language.CameraViewer.TakePhoto;
            this.Text = Language.CameraViewer.Camera;
            lblBig.Text = Language.CameraViewer.Big;
            lblThumb.Text = Language.CameraViewer.Thumbnail;
            lblEmails.Text = Language.CameraViewer.Emails;
            
        }

        private void Crop()
        {
            Rectangle cropRect = new Rectangle(secim.X * 8, secim.Y * 8, secim.Width * 8, secim.Height * 8);

            if (cropRect.Width > 0 && cropRect.Height > 0 && LatestImage != null)
            { 
                Bitmap cropped = new Bitmap(cropRect.Width, cropRect.Height);
                using (Graphics g = Graphics.FromImage(cropped))
                {
                    g.DrawImage(LatestImage, new Rectangle(0, 0, cropped.Width, cropped.Height),
                                     cropRect,
                                     GraphicsUnit.Pixel);
                }

                pbeMail.Image = cropped.Resize(100);
                pbThumbnail.Image = cropped.Resize(48);
                pbBig.Image = cropped.Resize(500);
                //pbShow.Image = cropped;
            }
        }


        private void InitCamera()
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            else
            {
                DirectoryInfo di = new DirectoryInfo(path);
                /*
                foreach (FileInfo fi in di.GetFiles())
                    fi.Delete();
                 */
            }

            CameraHandler = new SDKHandler();
            CameraHandler.DownloadCompleted += CameraHandler_DownloadCompleted;
            CameraHandler.CameraHasShutdown += CameraHandler_CameraHasShutdown;
            CameraHandler.ImageSaveDirectory = path;
            CameraHandler.ErrorOccured += CameraHandler_ErrorOccured;

            List<Camera> CamList = CameraHandler.GetCameraList();

            if (CamList.Count > 0)
            {
                Camera camera = CamList[0];
                this.Text = camera.Info.szDeviceDescription;
                CameraHandler.OpenSession(camera);

                CameraHandler.SetSetting(EDSDK.PropID_SaveTo, (uint)EDSDK.EdsSaveTo.Host);
                CameraHandler.SetCapacity();
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(Language.CameraViewer.NotFound, Language.Error , MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnTake.Enabled = false;
                //this.DialogResult = System.Windows.Forms.DialogResult.Abort;
            }
        }

        void CameraHandler_ErrorOccured(string error)
        {
            this.BeginInvoke((MethodInvoker)delegate() { this.lblError.Text = error; ;});
        }

        public Image LatestImage
        {
            get
            {
                //string pathT = path.Replace(".JPG", "-unsharpened.JPG");
                //KalikoImage sharpimg = new KalikoImage(path).GetThumbnailImage(1068, 710, ThumbnailMethod.Fit);     //427,284
                //sharpimg.ApplyFilter(new UnsharpMaskFilter(1.2, 0.4));
                //sharpimg.SaveJPG(pathT, 95);
                return pbOriginal.Image;
            }
            set
            {
                pbOriginal.Image = value;
            }
        }

        void CameraHandler_DownloadCompleted(string path)
        {
            latestFile = path;
            Image bmp = Bitmap.FromFile(latestFile);
            pbOriginal.Image = bmp;
            SetAllignment();
            Crop();
        }

        public void SetAllignment()
        {
            if (LatestImage == null)
            {
                pbOriginal.Width = 534;
                pbOriginal.Height = 356;
            }
            else
            {
                if (LatestImage.Width > LatestImage.Height)
                {
                    pbOriginal.Width = 534;
                    pbOriginal.Height = 356;
                }
                else
                {
                    pbOriginal.Width = 356;
                    pbOriginal.Height = 534;
                }
            }
        }



        private void btnTake_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                pbOriginal.Image = null;
                this.lblError.Text = "";
                CameraHandler.TakePhoto();
                this.Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.Default;
                DevExpress.XtraEditors.XtraMessageBox.Show(Language.Error + ":" + ex.ToString(), Language.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }
         

        private void btnLeft_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            pbOriginal.Image.RotateFlip(RotateFlipType.Rotate90FlipXY);
            pbOriginal.Invalidate();
            Crop();
            int a = pbOriginal.Width;
            pbOriginal.Width = pbOriginal.Height;
            pbOriginal.Height = a;
            
            this.Cursor = Cursors.Default;
        }

        private void btnRight_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            pbOriginal.Image.RotateFlip(RotateFlipType.Rotate270FlipXY);
            pbOriginal.Invalidate();
            Crop();
            int a = pbOriginal.Width;
            pbOriginal.Width = pbOriginal.Height;
            pbOriginal.Height = a;

            this.Cursor = Cursors.Default;
        }




        bool draw = false;
        Point First = new Point(0, 0);
        Point Last = new Point(0, 0);

        private void pb_MouseDown(object sender, MouseEventArgs e)
        {
            draw = true;
            First = new Point(e.X, e.Y);
        }

        private void pb_MouseUp(object sender, MouseEventArgs e)
        {
            draw = false;

            Crop();
        }

        private void pb_MouseMove(object sender, MouseEventArgs e)
        {
            if (draw)
            {
                Last = new Point(e.X, e.Y);
                pbOriginal.Refresh();
            }
        }

        Rectangle secim = new Rectangle(200, 100, 200, 200);
        Pen pen = new Pen(Brushes.Red);

        private void pb_Paint(object sender, PaintEventArgs e)
        {
            int fark = Last.X - First.X;
            if (Last.Y - First.Y > fark)
                fark = Last.Y - First.Y;

            if (draw)
            {
                e.Graphics.DrawRectangle(pen, secim);
                secim = new Rectangle(First.X, First.Y, fark, fark);
            }
            else
            {
                e.Graphics.DrawRectangle(pen, secim);
            }
        }

        int productId = 0;
        private void TakeGo_Click(object sender, EventArgs e)
        {
            string imageBackupPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\AkerPhotos";
            this.Cursor = Cursors.WaitCursor;
            //byte[] thumb = ct.LatestImage
            //     .CropFromCenter(1500)
            //     .Resize(32)
            //     .Unsharpen()
            //     .ToJPEG();

            if (productId > 0)
            {
                pbOriginal.Image.Save(imageBackupPath + "\\" + productId + "_original.jpg");
                pbBig.Image.Save(imageBackupPath + "\\" + productId + "_big.jpg");
                pbeMail.Image.Save(imageBackupPath + "\\" + productId + "_email.jpg");
                pbThumbnail.Image.Save(imageBackupPath + "\\" + productId + "_thumbnail.jpg");


                Data.DM.ExecuteNonQuery("EditPhoto", productId,                    
                    pbBig.Image.ToJPEG(),
                    pbeMail.Image.ToJPEG(),
                    pbThumbnail.Image.ToJPEG());
            }

            DataTable dt = Data.DM.ExecuteDataTableByQuery("select top 1 * from Photo(nolock) where Thumbnail is null and original is not null");
            if (dt.Rows.Count == 1)
            {
                pbOriginal.Image = Image.FromStream(new MemoryStream((byte[])dt.Rows[0]["Original"]));
                SetAllignment();
                Crop();
                productId = dt.Rows[0]["ProductId"].ToIntNN();
                this.Text = productId.ToString();
            }

            this.Cursor = Cursors.Default;
        }
    }
}